package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.PutCache;
import service.Util;

import model.News;
import model.NewsRecent;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class TinnhanhServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		try {
			ObjectifyService.register(News.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		Objectify objectify = ObjectifyService.begin();
		
		ArrayList<NewsRecent> newUpdate = PutCache.getCacheNews("newUpdate");
		if(newUpdate.size()<=0)
		{
			Query<News> list = objectify.query(News.class).order("-date").limit(15);
			ArrayList<News> arrayList = Util.convertArrayList(list);
			
			for(int i=(arrayList.size()-1);i>=0;i--)
			{
				NewsRecent newsRecent = new NewsRecent();
				newsRecent.setDate(arrayList.get(i).getDate());
				newsRecent.setThumb(arrayList.get(i).getThumb());
				newsRecent.setTitle(arrayList.get(i).getTitle().getValue());
				newsRecent.setCategory(arrayList.get(i).getCategory());
				newsRecent.setDes(Util.cutDescription(arrayList.get(i).getContent().getValue()));
				
				PutCache.putCacheNews(newsRecent, "newUpdate", 15);
			}
		}
		
		ArrayList<String> category = PutCache.getCacheList("category");
	
		if(category.size()>0)
		{
			for (int j = 0; j < category.size(); j++) {
				ArrayList<NewsRecent> cacheCcategory = PutCache.getCacheNews(category.get(j));
				if(cacheCcategory.size()<=0)
				{
					Query<News> list1 = objectify.query(News.class).filter("categoryAlias", category.get(j)).order("-date").limit(5);

					ArrayList<News> arrayList = Util.convertArrayList(list1);
					
					for(int i=(arrayList.size()-1);i>=0;i--)
					{
						NewsRecent newsRecent = new NewsRecent();
						newsRecent.setDate(arrayList.get(i).getDate());
						newsRecent.setThumb(arrayList.get(i).getThumb());
						newsRecent.setTitle(arrayList.get(i).getTitle().getValue());
						newsRecent.setCategory(arrayList.get(i).getCategory());
						newsRecent.setDes(Util.cutDescription(arrayList.get(i).getContent().getValue()));
						
						PutCache.putCacheNews(newsRecent, category.get(j), 5);
					}
					
				}
			}
		}
		
		try {
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
